package com.jmuok.web.fff.web;

import java.util.Locale;

import com.vaadin.Application;
import com.vaadin.data.Property.ValueChangeEvent;
import com.vaadin.data.Property.ValueChangeListener;
import com.vaadin.terminal.ThemeResource;
import com.vaadin.ui.ComboBox;
import com.vaadin.ui.Select;

public class LocaleBoxComponet implements LocaleSelectable {
	private ComboBox localeBox;

	public LocaleBoxComponet(String caption) {
		localeBox = new ComboBox(caption);
	}

	@Override
	public Select initLocaleBox(final Application app) {
		Locale[] supportedLocals = { Locale.SIMPLIFIED_CHINESE, Locale.JAPAN };
		String[] sNames = { "cn", "jp" };

		localeBox.setNullSelectionAllowed(false);
		localeBox.setImmediate(true);
		localeBox.setTextInputAllowed(false);
		localeBox.setWidth("140px");

		for (int i = 0; i < supportedLocals.length; i++) {
			localeBox.addItem(supportedLocals[i]);
			localeBox.setItemCaption(supportedLocals[i],
					supportedLocals[i].getDisplayName(supportedLocals[i]));
			localeBox.setItemIcon(supportedLocals[i], new ThemeResource(
					"../web/flags/" + sNames[i] + ".gif"));
			// Automatically select the current locale
			if (supportedLocals[i].equals(app.getLocale()))
				localeBox.setValue(supportedLocals[i]);
		}
		localeBox.addListener(new ValueChangeListener() {
			private static final long serialVersionUID = 1L;

			@Override
			public void valueChange(ValueChangeEvent event) {
				app.setLocale((Locale) event.getProperty().getValue());
				//TODO app close is aright?
				app.close();
			}
		});
		return localeBox;
	}

}
